<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input 
          v-model="queryParams.className" 
          placeholder="请输入班级名称" 
          clearable 
          style="width: 240px" 
          @keyup.enter="handleQuery" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="班级名称" align="center" prop="className" :formatter="formatClassName" width="200"/>
      <el-table-column label="单选题得分率" align="center">
        <template #default="scope">
          <el-tooltip :content="scope.row.singleChoiceScoreDetail" placement="top">
            <span :class="getScoreClass(scope.row.singleChoiceRatio)">
              {{ scope.row.singleChoiceRatio + '%' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="多选题得分率" align="center">
        <template #default="scope">
          <el-tooltip :content="scope.row.multiChoiceScoreDetail" placement="top">
            <span :class="getScoreClass(scope.row.multiChoiceRatio)">
              {{ scope.row.multiChoiceRatio + '%' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="判断题得分率" align="center">
        <template #default="scope">
          <el-tooltip :content="scope.row.judgmentScoreDetail" placement="top">
            <span :class="getScoreClass(scope.row.judgmentRatio)">
              {{ scope.row.judgmentRatio + '%' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="填空题得分率" align="center">
        <template #default="scope">
          <el-tooltip :content="scope.row.fillBlankScoreDetail" placement="top">
            <span :class="getScoreClass(scope.row.fillBlankRatio)">
              {{ scope.row.fillBlankRatio + '%' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="简答题得分率" align="center">
        <template #default="scope">
          <el-tooltip :content="scope.row.shortAnswerScoreDetail" placement="top">
            <span :class="getScoreClass(scope.row.shortAnswerRatio)">
              {{ scope.row.shortAnswerRatio + '%' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleViewStudents(scope.row)" v-hasPermi="['manage:analysis:list']">进入班级</el-button>
          <el-button link type="primary" icon="Document" @click="handleAnalysis(scope.row)" v-hasPermi="['manage:analysis:list']">成绩分析</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="ClassAnalysis">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getClassList } from '@/api/manage/analysis';
import { getMyClasses } from '@/api/manage/grade';
import useUserStore from '@/store/modules/user'

// 用户信息
const userStore = useUserStore();
const isAdmin = ref(userStore.roles.includes('admin'));

// 路由对象
const router = useRouter();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 班级表格数据
const classList = ref([]);
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  className: undefined
});

/** 查询班级列表 */
function getList() {
  loading.value = true;
  getClassList(queryParams).then(response => {
    // 处理响应数据，进行字段映射
    const formattedData = response.rows.map(item => ({
      ...item,
      // 将下划线命名转为驼峰命名
      className: item.className || item.class_name,
      classId: item.classId || item.class_id
    }));
    
    // 对班级列表按照班级ID排序（从小到大）
    classList.value = formattedData.sort((a, b) => a.classId - b.classId);
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error('获取班级列表失败:', error);
    loading.value = false;
  });
}

// 格式化班级名称，兼容两种命名方式
function formatClassName(row) {
  return row.className || row.class_name;
}

// 取消按钮
function cancel() {
  reset();
}

// 表单重置
function reset() {
  // 清空表单
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // resetForm("queryForm");
  queryParams.className = undefined;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.classId || item.class_id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 查看班级学生按钮操作 */
function handleViewStudents(row) {
  router.push({ path: '/analysis/student', query: { classId: row.classId || row.class_id } });
}

/** 班级成绩分析按钮操作 */
function handleAnalysis(row) {
  router.push({ path: '/analysis/class-detail', query: { classId: row.classId || row.class_id } });
}

/** 根据得分率获取对应的CSS类名 */
function getScoreClass(scoreRatio) {
  if (scoreRatio >= 90) {
    return 'score-excellent';
  } else if (scoreRatio >= 80) {
    return 'score-good';
  } else if (scoreRatio >= 60) {
    return 'score-pass';
  } else {
    return 'score-fail';
  }
}

// 修改 handleDetail 方法，使用新的路由路径
function handleDetail(row) {
  router.push({
    path: '/analysis/class-detail',
    query: {
      classId: row.classId
    }
  });
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #303133;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}
</style>

